# 导入模块
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains
import os
import time


# 定义Logon类
class Logon:
    # 初始化数据
    def __init__(self):
        # 打开浏览器
        self.driver = webdriver.Chrome()
        # 浏览器最大化
        self.driver.maximize_window()

        # 请求访问网址
        # 准备url
        url = 'file:///' + os.path.abspath('html') + '/注册实例.html'
        self.driver.get(url)

        # 准备注册数据
        self.UserInfo = {
            'user': '小小怪下士',
            'password': '123456',
            'phone': '1231231',
            'email': '123@163.com'
        }

    def use_logon(self):
        # TODO 注册用户表单
        # 定位账号输入框,输入数据
        self.driver.find_element(By.ID, 'user').send_keys(self.UserInfo['user'])
        # 定位密码输入框，输入数据
        self.driver.find_element(By.ID, 'password').send_keys(self.UserInfo['password'])
        # 定位电话号码输入框，输入数据
        self.driver.find_element(By.ID, 'tel').send_keys(self.UserInfo['phone'])
        # 定位电子邮件输入框，输入数据
        self.driver.find_element(By.ID, 'email').send_keys(self.UserInfo['email'])

        # TODO 下拉框操作
        # 定位下拉框位置
        se = self.driver.find_element(By.XPATH, '//*[@id="select"]')
        # 创建select对象,参数是要操作的标签
        select = Select(se)
        # 选择option
        # 通过value选取
        select.select_by_value('gz')

        # TODO alert操作
        # 定位alert按钮并点击
        btn = self.driver.find_element(By.ID, 'alert')
        # 创建动作对象
        ac = ActionChains(driver=self.driver)
        # 绑定鼠标事件,perform调用
        ac.click(btn).perform()
        # 切换到弹窗
        alert = self.driver.switch_to.alert
        # 点击确定
        alert.accept()

    def click_register(self):
        # 定位注册按钮位置并点击
        self.driver.find_element(By.XPATH, '//*[@id="zc"]/fieldset/button').click()

    def quit(self):
        # 退出浏览器
        self.driver.quit()


if __name__ == '__main__':
    i = Logon()
    i.use_logon()
    time.sleep(3)
    i.click_register()
    time.sleep(3)
    i.quit()
